# -*- encoding: utf-8 -*-
##############################################################################
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

# from odoo import models, api
from odoo import models, fields, api, _
import odoo.addons.decimal_precision as dp
from odoo.exceptions import ValidationError
from odoo.tools.float_utils import float_compare
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
import time


class choose_product(models.TransientModel):
    _name = 'choose.product'
    _description = 'choose product'
    _rec_name = 'product_id'
    # _order = 'date desc'

    id = fields.Integer('Id')
    mrp_bom_line_id = fields.Many2one('mrp.bom.line', u'bom明细行')
    product_id = fields.Many2one('product.product', u'产品')
    product_qty = fields.Float(u'用量')
    replace_products = fields.Text(u"替代料", compute='_compute_replace_products')
    mrp_product_replace_id = fields.Many2one('mrp.product.replace', u'替代为')
    replace_product_qty = fields.Float(u'替代品用量', default=0.0)
    attrition_rate = fields.Float(u'耗损率', default=0.0)
    attrition_fixed = fields.Float(u'固定耗损', default=0.0)
    new_replace_product_id = fields.Many2one('product.product', u'新增替代产品')
    stock_move_id = fields.Many2one('stock.move', u'移动')
    production_id = fields.Many2one('mrp.production', u'生产单')

    @api.one
    @api.depends('product_id')
    def _compute_replace_products(self):
        replace = ""
        replace_products = self.env['mrp.product.replace'].search(
            [('name', '=', self.product_id.id), ('mrp_bom_line_id', '=', self.mrp_bom_line_id.id)])
        for r in replace_products:
            replace += r.display_name
        self.replace_products = replace

    @api.onchange('mrp_product_replace_id')
    def _onchange_mrp_product_replace_id(self):
        if self.mrp_product_replace_id:
            self.replace_product_qty = self.mrp_product_replace_id.replace_product_qty
            self.attrition_rate = self.mrp_product_replace_id.attrition_rate
            self.attrition_fixed = self.mrp_product_replace_id.attrition_fixed

    @api.model
    def create(self, context):
        vals = {}
        if context:
            vals = context
            move = self.env['stock.move'].browse(vals.get('stock_move_id'))
            bom_line = self.env['mrp.bom.line'].browse(vals.get('bom_line_id'))
            if move:
                vals['product_id'] = move.product_id.id
                vals['product_qty'] = move.bom_line_id.product_qty
                vals['mrp_bom_line_id'] = move.bom_line_id.id
                vals['replace_product_qty'] = move.bom_line_id.product_qty
                vals['attrition_rate'] = move.bom_line_id.attrition_rate
                vals['attrition_fixed'] = move.bom_line_id.attrition_fixed
                vals['production_id'] = move.raw_material_production_id.id
            elif bom_line:
                vals['product_id'] = bom_line.product_id.id
                vals['product_qty'] = bom_line.product_qty
                vals['mrp_bom_line_id'] = bom_line.id
                vals['replace_product_qty'] = bom_line.product_qty
                vals['attrition_rate'] = bom_line.attrition_rate
                vals['attrition_fixed'] = bom_line.attrition_fixed
        new_id = super(choose_product, self).create(vals)
        return new_id

    @api.multi
    def save(self):
        for data in self.browse(self.ids[0]):
            if data.mrp_product_replace_id:
                # 取消库存占用
                data.stock_move_id.do_unreserve()
                # 取消原明细行，然后将bom_line的信息修改，改产品，数量，耗损，然后执行方法。执行后再改回来。
                # 保存原信息
                old_product_id = data.mrp_bom_line_id.product_id
                old_product_qty = data.mrp_bom_line_id.product_qty
                old_attrition_rate = data.mrp_bom_line_id.attrition_rate
                old_attrition_fixed = data.mrp_bom_line_id.attrition_fixed
                # 取消原明细行
                data.stock_move_id.action_cancel()
                # 修改bom明细信息
                data.mrp_bom_line_id.product_id = data.mrp_product_replace_id.replace_product_id.id
                data.mrp_bom_line_id.product_qty = data.replace_product_qty
                data.mrp_bom_line_id.attrition_rate = data.attrition_rate
                data.mrp_bom_line_id.attrition_fixed = data.attrition_fixed
                # 执行方法
                move = data.production_id._generate_raw_move(data.mrp_bom_line_id,
                                                             {'qty': data.replace_product_qty, 'parent_line': None})
                data.production_id._adjust_procure_method()
                move.action_confirm()

                # 还原bom明细信息
                data.mrp_bom_line_id.product_id = old_product_id.id
                data.mrp_bom_line_id.product_qty = old_product_qty
                data.mrp_bom_line_id.attrition_rate = old_attrition_rate
                data.mrp_bom_line_id.attrition_fixed = old_attrition_fixed

            elif data.new_replace_product_id:
                vals = {
                    'name': data.product_id.id,
                    'replace_product_id': data.new_replace_product_id.id,
                    'mrp_bom_line_id': data.mrp_bom_line_id.id,
                    'replace_product_qty': data.replace_product_qty,
                    'attrition_rate': data.attrition_rate,
                    'attrition_fixed': data.attrition_fixed,
                }
                self.env['mrp.product.replace'].create(vals)
            else:
                raise ValidationError(u'请选择执行的替代物料，或者填入新增的替代物料!否则请关闭当前页。')
        return {'type': 'ir.actions.act_window_close'}
